<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Type Ahead</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="contant">
        <input type="text" class="serch-input" placeholder="请输入城市名称/拼音" />
        <ul class="result">
            <li>没有匹配结果</li>
        </ul>
    </div>
    <script>
        let input = document.querySelector(".serch-input")
        let ulresult = document.querySelector(".result")
        let cities = {}
        fetch('http://localhost:8090/mork/city.json', {
            mode: 'cors'
        }).then(blob => blob.json()).then(data => {
            cities = data.data.cities
        })

        function displayMatches() {
            const result = []
            //获取匹配的城市
            for (let i in cities) {
                cities[i].forEach((value) => {
                    if (value.spell.indexOf(this.value) > -1 || value.name.indexOf(this.value) > -1) {
                        result.push(value)
                    }
                })
            }

            //给匹配的字符添加高亮
            const html = result.map(place => {
                const regex = new RegExp(this.value, 'gi')
                const cityName = place.name.replace(regex, `<span class='h1'>${this.value}</span>`)
                const citySpell = place.spell.replace(regex, `<span class='h1'>${this.value}</span>`)
                return `<li>
                            <span class='name'>${cityName},${citySpell}</span>
                        </li>`
            }).join('')

            ulresult.innerHTML = html
            if (result.length == 0 || !this.value) {
                ulresult.innerHTML = `<li>没有匹配结果</li>`
            }
        }
        input.addEventListener('change', displayMatches)
        input.addEventListener('keyup', displayMatches)
    </script>
</body>

</html>